package com.tuozixuan;

import static com.tuozixuan.GitDemoConstants.LOCAL_DIR;
import static com.tuozixuan.GitDemoConstants.PASSWORD;
import static com.tuozixuan.GitDemoConstants.USERNAME;

import java.io.File;
import java.util.List;

import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class GitCheckoutDemo {

	public static void main(String[] args) throws Exception {
		
		Git git = Git.open(new File(LOCAL_DIR));
		UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(USERNAME, PASSWORD);
		// 拉取远程更新        
		String branchName = "master";
		git.pull().setCredentialsProvider(provider).setRemoteBranchName(branchName).call();
		boolean existBranch = false;
		//列出所有的分支名称，判断分支是否存在
		List<Ref> branchList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
		//String branchName = featureInfo.getBranchVersion();
		for (Ref ref : branchList) {
		    if (("refs/remotes/origin/" + branchName).equals(ref.getName())) {
		        existBranch = true;
		    }
		}
		if (!existBranch) {
		    //log.error("分支{}不存在，请确认", branchName);
		}
		boolean existLocalBranch = false;
		List<Ref> branchList1 = git.branchList().call();
		for (Ref ref : branchList1) {
		    if (ref.getName().equals("refs/heads/" + branchName)) {
		        existLocalBranch = true;
		    }
		}
		if (existLocalBranch) {
		    // 存在则切换本地分支
		    git.checkout().setName(branchName).call();
		} else {
		    // 不存在则切换为远程分支
		    git.checkout().setCreateBranch(true).setName(branchName)
		            .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
		            .setStartPoint("origin/" + branchName).call();
		}
	}

}
